<template>
  <div class="text-diff-tool">
    <div class="tool-header">
      <h1>文本对比</h1>
      <p>对比两个文本的差异</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 对比主体 -->
        <el-col :span="24">
          <div class="diff-section">
            <!-- 输入区域 -->
            <div class="input-section">
              <div class="input-group">
                <div class="input-header">
                  <h3>文本A</h3>
                  <div class="input-actions">
                    <el-button @click="pasteTextA" size="small">
                      <el-icon><DocumentCopy /></el-icon>
                      粘贴
                    </el-button>
                    <el-button @click="clearTextA" size="small">
                      清空
                    </el-button>
                    <el-button @click="loadSampleA" size="small">
                      示例
                    </el-button>
                  </div>
                </div>
                <el-input
                  v-model="textA"
                  type="textarea"
                  :rows="8"
                  placeholder="请输入第一个文本..."
                  class="text-input"
                />
              </div>
              
              <div class="input-group">
                <div class="input-header">
                  <h3>文本B</h3>
                  <div class="input-actions">
                    <el-button @click="pasteTextB" size="small">
                      <el-icon><DocumentCopy /></el-icon>
                      粘贴
                    </el-button>
                    <el-button @click="clearTextB" size="small">
                      清空
                    </el-button>
                    <el-button @click="loadSampleB" size="small">
                      示例
                    </el-button>
                  </div>
                </div>
                <el-input
                  v-model="textB"
                  type="textarea"
                  :rows="8"
                  placeholder="请输入第二个文本..."
                  class="text-input"
                />
              </div>
            </div>
            
            <!-- 对比选项 -->
            <div class="diff-options">
              <h3>对比选项</h3>
              <div class="options-grid">
                <div class="option-group">
                  <label>对比模式：</label>
                  <el-select v-model="diffMode" size="small">
                    <el-option label="逐行对比" value="line" />
                    <el-option label="逐字符对比" value="character" />
                    <el-option label="逐词对比" value="word" />
                  </el-select>
                </div>
                <div class="option-group">
                  <label>忽略空白：</label>
                  <el-switch v-model="ignoreWhitespace" size="small" />
                </div>
                <div class="option-group">
                  <label>忽略大小写：</label>
                  <el-switch v-model="ignoreCase" size="small" />
                </div>
                <div class="option-group">
                  <label>显示上下文：</label>
                  <el-input-number v-model="contextLines" :min="0" :max="10" size="small" />
                </div>
              </div>
            </div>
            
            <!-- 对比按钮 -->
            <div class="diff-actions">
              <el-button @click="compareTexts" type="primary" size="large" :loading="isComparing" :disabled="!textA.trim() || !textB.trim()">
                <el-icon><Search /></el-icon>
                开始对比
              </el-button>
              <el-button @click="clearAll" size="large">
                清空全部
              </el-button>
              <el-button @click="exportDiff" size="large" :disabled="!diffResult">
                <el-icon><Download /></el-icon>
                导出结果
              </el-button>
            </div>
            
            <!-- 对比结果 -->
            <div class="diff-result" v-if="diffResult">
              <h3>对比结果</h3>
              <div class="result-summary">
                <div class="summary-item">
                  <div class="summary-label">相同行数</div>
                  <div class="summary-value same">{{ diffResult.sameLines }}</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">新增行数</div>
                  <div class="summary-value added">{{ diffResult.addedLines }}</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">删除行数</div>
                  <div class="summary-value removed">{{ diffResult.removedLines }}</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">修改行数</div>
                  <div class="summary-value modified">{{ diffResult.modifiedLines }}</div>
                </div>
              </div>
              
              <div class="diff-content">
                <div class="diff-viewer">
                  <div 
                    v-for="(line, index) in diffResult.lines" 
                    :key="index"
                    class="diff-line"
                    :class="getLineClass(line.type)"
                  >
                    <div class="line-number">{{ line.lineNumber }}</div>
                    <div class="line-type">{{ line.type }}</div>
                    <div class="line-content">{{ line.content }}</div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 对比历史 -->
            <div class="diff-history">
              <h3>对比历史</h3>
              <div class="history-list">
                <div 
                  v-for="(item, index) in diffHistory" 
                  :key="index"
                  class="history-item"
                  @click="loadFromHistory(item)"
                >
                  <div class="history-info">
                    <span class="history-mode">{{ item.mode }}</span>
                    <span class="history-changes">{{ item.changes }} 处差异</span>
                    <span class="history-time">{{ item.time }}</span>
                  </div>
                </div>
                <div v-if="diffHistory.length === 0" class="empty-history">
                  暂无对比历史
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { DocumentCopy, Search, Download } from '@element-plus/icons-vue'

const textA = ref('')
const textB = ref('')
const diffMode = ref('line')
const ignoreWhitespace = ref(false)
const ignoreCase = ref(false)
const contextLines = ref(3)
const isComparing = ref(false)
const diffResult = ref(null)
const diffHistory = ref([])

const sampleTextA = `Hello World!
This is a sample text.
It contains multiple lines.
We can compare it with another text.`

const sampleTextB = `Hello Universe!
This is a sample text.
It contains multiple lines.
We can compare it with another text.
This is an additional line.`

const pasteTextA = async () => {
  try {
    const text = await navigator.clipboard.readText()
    textA.value = text
    ElMessage.success('文本A已粘贴')
  } catch (error) {
    ElMessage.error('无法访问剪贴板')
  }
}

const pasteTextB = async () => {
  try {
    const text = await navigator.clipboard.readText()
    textB.value = text
    ElMessage.success('文本B已粘贴')
  } catch (error) {
    ElMessage.error('无法访问剪贴板')
  }
}

const clearTextA = () => {
  textA.value = ''
  ElMessage.info('文本A已清空')
}

const clearTextB = () => {
  textB.value = ''
  ElMessage.info('文本B已清空')
}

const loadSampleA = () => {
  textA.value = sampleTextA
  ElMessage.success('示例文本A已加载')
}

const loadSampleB = () => {
  textB.value = sampleTextB
  ElMessage.success('示例文本B已加载')
}

const clearAll = () => {
  textA.value = ''
  textB.value = ''
  diffResult.value = null
  ElMessage.info('已清空全部内容')
}

const compareTexts = async () => {
  if (!textA.value.trim() || !textB.value.trim()) {
    ElMessage.warning('请输入两个文本进行对比')
    return
  }
  
  isComparing.value = true
  
  try {
    // 模拟对比过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 简单的文本对比逻辑
    const linesA = textA.value.split('\n')
    const linesB = textB.value.split('\n')
    
    const diffLines = []
    let sameLines = 0
    let addedLines = 0
    let removedLines = 0
    let modifiedLines = 0
    
    const maxLines = Math.max(linesA.length, linesB.length)
    
    for (let i = 0; i < maxLines; i++) {
      const lineA = linesA[i] || ''
      const lineB = linesB[i] || ''
      
      if (lineA === lineB) {
        diffLines.push({
          lineNumber: i + 1,
          type: 'same',
          content: lineA
        })
        sameLines++
      } else if (!lineA) {
        diffLines.push({
          lineNumber: i + 1,
          type: 'added',
          content: lineB
        })
        addedLines++
      } else if (!lineB) {
        diffLines.push({
          lineNumber: i + 1,
          type: 'removed',
          content: lineA
        })
        removedLines++
      } else {
        diffLines.push({
          lineNumber: i + 1,
          type: 'modified',
          content: `A: ${lineA} | B: ${lineB}`
        })
        modifiedLines++
      }
    }
    
    diffResult.value = {
      sameLines,
      addedLines,
      removedLines,
      modifiedLines,
      lines: diffLines
    }
    
    // 添加到历史
    addToHistory()
    
    ElMessage.success('文本对比完成')
    
  } catch (error) {
    ElMessage.error('对比失败：' + error.message)
  } finally {
    isComparing.value = false
  }
}

const getLineClass = (type) => {
  switch (type) {
    case 'same': return 'same'
    case 'added': return 'added'
    case 'removed': return 'removed'
    case 'modified': return 'modified'
    default: return ''
  }
}

const exportDiff = () => {
  if (!diffResult.value) return
  
  const content = `文本对比结果
================

相同行数: ${diffResult.value.sameLines}
新增行数: ${diffResult.value.addedLines}
删除行数: ${diffResult.value.removedLines}
修改行数: ${diffResult.value.modifiedLines}

详细对比:
${diffResult.value.lines.map(line => `${line.lineNumber}: [${line.type}] ${line.content}`).join('\n')}`
  
  const blob = new Blob([content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'text-diff-result.txt'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('对比结果已导出')
}

const addToHistory = () => {
  const historyItem = {
    mode: diffMode.value,
    changes: diffResult.value.addedLines + diffResult.value.removedLines + diffResult.value.modifiedLines,
    time: new Date().toLocaleString('zh-CN')
  }
  
  diffHistory.value.unshift(historyItem)
  
  // 限制历史记录数量
  if (diffHistory.value.length > 20) {
    diffHistory.value = diffHistory.value.slice(0, 20)
  }
}

const loadFromHistory = (item) => {
  ElMessage.success(`已加载：${item.mode} 对比历史`)
}
</script>

<style scoped>
.text-diff-tool {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.diff-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.input-section,
.diff-options,
.diff-actions,
.diff-result,
.diff-history {
  margin-bottom: 30px;
}

.input-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.input-group {
  display: flex;
  flex-direction: column;
}

.input-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.input-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.2rem;
}

.input-actions {
  display: flex;
  gap: 8px;
}

.text-input {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.diff-options h3,
.diff-result h3,
.diff-history h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.3rem;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.option-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-group label {
  font-weight: 500;
  color: #666;
}

.diff-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.result-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.summary-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  border: 1px solid #e9ecef;
}

.summary-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 1.5rem;
  font-weight: bold;
}

.summary-value.same {
  color: #28a745;
}

.summary-value.added {
  color: #20c997;
}

.summary-value.removed {
  color: #dc3545;
}

.summary-value.modified {
  color: #ffc107;
}

.diff-content {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e9ecef;
  max-height: 500px;
  overflow-y: auto;
}

.diff-viewer {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.diff-line {
  display: grid;
  grid-template-columns: 60px 80px 1fr;
  gap: 10px;
  padding: 5px 0;
  border-bottom: 1px solid #e9ecef;
}

.diff-line:last-child {
  border-bottom: none;
}

.diff-line.same {
  background: #f8f9fa;
}

.diff-line.added {
  background: #d4edda;
}

.diff-line.removed {
  background: #f8d7da;
}

.diff-line.modified {
  background: #fff3cd;
}

.line-number {
  color: #666;
  text-align: right;
  font-weight: bold;
}

.line-type {
  color: #333;
  font-weight: bold;
  text-align: center;
}

.line-type::before {
  content: '';
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 5px;
}

.diff-line.same .line-type::before {
  background: #28a745;
}

.diff-line.added .line-type::before {
  background: #20c997;
}

.diff-line.removed .line-type::before {
  background: #dc3545;
}

.diff-line.modified .line-type::before {
  background: #ffc107;
}

.line-content {
  color: #333;
  word-break: break-all;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.history-item:hover {
  background: #e9ecef;
  transform: translateY(-1px);
}

.history-info {
  display: flex;
  gap: 15px;
  font-size: 0.9rem;
  color: #666;
}

.history-mode {
  color: #667eea;
  font-weight: 500;
}

.history-changes {
  color: #28a745;
  font-weight: 500;
}

.history-time {
  color: #999;
}

.empty-history {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-style: italic;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .input-section {
    grid-template-columns: 1fr;
  }
  
  .options-grid {
    grid-template-columns: 1fr;
  }
  
  .diff-actions {
    flex-direction: column;
  }
  
  .result-summary {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .diff-line {
    grid-template-columns: 1fr;
    gap: 5px;
  }
  
  .line-number,
  .line-type {
    text-align: left;
  }
  
  .history-info {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
